package cn.chenxing.module.main.service;

import cn.chenxing.domain.threadlocal.ThreadLocalInfo;
import cn.chenxing.domain.util.AlertUtil;
import cn.chenxing.domain.util.IOConvertUtil;
import cn.chenxing.module.user.entity.VenusUserInfoEntity;
import cn.chenxing.module.user.service.VenusUserInfoService;
import cn.chenxing.utils.SftpUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jfoenix.controls.JFXButton;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Description
 * @Author maogen.ymg
 * @Date 2020/3/13 10:07
 */
@Service
@Slf4j
public class MainService {

    @Resource
    private VenusUserInfoService userInfoService;

    /**用户名**/
    private String userName;

    /**
     * 设置头像
     * @param headImage 头像控件
     */
    public void setHeadImage(JFXButton headImage){
        // 不能全局变量赋值，否则获取不到最新的值
        userName = ThreadLocalInfo.get().getUserName();

        if("同学".equals(userName)){
            headImage.setStyle("-fx-background-image: url(/images/head/default_head.png)");
            return;
        }
        VenusUserInfoEntity sqlUserInfoEntity = userInfoService.getOne(
                new QueryWrapper<VenusUserInfoEntity>().eq("user_name", userName));
        byte[] imageByte = SftpUtil.downloadToBytes(sqlUserInfoEntity.getHeadPath());

        headImage.setGraphic(new ImageView(new Image(new ByteArrayInputStream(imageByte))));
    }

    /**
     * 上传头像
     * @param filepath 路径
     * @param width 宽度
     * @param height 高度
     * @return 是否成功
     */
    public boolean uploadHeadImage(String filepath, int width, int height){
        if(filepath == null){
            return false;
        }
        String errorMessage;
        try {
            // 处理图片
            BufferedImage formatAvatarImage = setProcessedHead(filepath, width, height);
            // 输出上传图片
            InputStream inputStream = IOConvertUtil.bufferedImageToInputStream(formatAvatarImage, "png");
            String remoteDirectory = SftpUtil.getRemoteDirectory().concat("headImages/");
            String fileName = userName.concat("_head.png");
            boolean isUpload = SftpUtil.upload(remoteDirectory, fileName, inputStream);

            if(isUpload){
                VenusUserInfoEntity sqlUserInfoEntity = new VenusUserInfoEntity();
                sqlUserInfoEntity.setHeadPath(remoteDirectory.concat(fileName));
                boolean isUpdate = userInfoService.update(sqlUserInfoEntity, new QueryWrapper<VenusUserInfoEntity>().eq("user_name", userName));

                if(isUpdate) {
                    log.info("上传头像成功");
                    return true;
                }else {
                    errorMessage = "上传头像错误, 更新数据库表失败";
                }

            }else {
                errorMessage = "上传头像错误, 上传文件远端失败";
            }

        }catch (IOException e){
            errorMessage = "上传头像错误" + e.getMessage();
        }
        log.error(errorMessage);
        AlertUtil.showErrorAlert(errorMessage+ "  请重试!");
        return false;
    }

    /**
     * 处理头像为圆形
     * @param filepath 路径
     * @param width 宽度
     * @param height 高度
     * @throws IOException IOException
     */
    private BufferedImage setProcessedHead(String filepath, int width, int height) throws IOException {

        // 图片的本地地址
        BufferedImage src = ImageIO.read(new File(filepath));
        // 透明底的图片
        BufferedImage formatAvatarImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = formatAvatarImage.createGraphics();
        //把图片切成一个圆
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //留一个像素的空白区域，画圆的时候把这个覆盖
        int border = 1;
        //图片是一个圆型
        Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width - border * 2.0, height - border * 2.0);
        //需要保留的区域
        graphics.setClip(shape);
        graphics.drawImage(src, border, border, width - border * 2, height - border * 2, null);
        graphics.dispose();
        //在圆图外面再画一个圆
        //新创建一个graphics（这样画的圆不会有锯齿）
        graphics = formatAvatarImage.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        border = 3;
        //画笔是4.5个像素
        //使画笔时基本会像外延伸一定像素
        Stroke s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        graphics.setStroke(s);
        graphics.setColor(Color.WHITE);
        graphics.drawOval(border, border, width - border * 2, height - border * 2);
        graphics.dispose();

        return formatAvatarImage;

    }

    /**
     * 设置菜单图标
     * @param iconUrl 图标URL
     * @param menuButton 菜单按钮
     */
    public void setMenuIcon(String iconUrl, JFXButton menuButton){
        Image btnImg = new Image(iconUrl);
        ImageView imageView = new ImageView(btnImg);
        menuButton.setGraphic(imageView);
    }

    /**
     * 根据当前时间获取对应的欢迎语
     * @return 欢迎语
     */
    public String getWelcomeSpeech(){
        int hour = DateUtil.hour(DateUtil.date(),true);
        if(hour >= 6 && hour < 9){
            return "早上好";
        }else if(hour >= 9 && hour < 12){
            return "上午好";
        }else if(hour >= 12 && hour < 14){
            return "中午好";
        }else if(hour >= 14 && hour < 18){
            return "下午好";
        }else if(hour >= 18 && hour < 20){
            return "傍晚好";
        }else if(hour >= 20 && hour < 22){
            return "晚上好";
        }else if(hour >= 22 || hour < 3){
            return "深夜了，注意休息";
        }
        return "";
    }
}
